<?php
/**
 * 修复品牌全部分类下wiki
 * @author tangyiwan
 */

ini_set('display_errors', 1);
error_reporting(-1);
ini_set('memory_limit', '512M');
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brand\CustomCategoryWiki as mCustomCategoryWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;

$val = $argv[1] ?? '';
//$val = 1416;
if (is_numeric($val)) {
    $brandId = $val;
    repair($brandId);
} else if ($val == 'all') {
    $res = mWikiBasic::select(['brand_id', 'count' => \Medoo\Medoo::raw('COUNT(<id>)')], [
        'brand_id[>]' => 0,
        'basic_state[!]' => mWikiBasic::STATE_ONLINE,
        'GROUP' => 'brand_id',
        'ORDER' => ['count' => 'DESC'],
        'HAVING' => ['count[>=]' => 10]
    ]);
    foreach ($res as $row) {
        $brandId = $row['brand_id'];
        repair($brandId);
    }
    var_dump($res);
}

function repair($brandId)
{
    var_dump('修复品牌:' . $brandId);
    $delBasicIds = mWikiBasic::selectByWhere(['brand_id' => $brandId, 'basic_state[!]' => mWikiBasic::STATE_ONLINE], 'id');
    if (!empty($delBasicIds)) {
        foreach ($delBasicIds as $delId) {
            var_dump('查询品牌商品#删除自定义分类中非上线状态的品牌WIKI#brand_id:' . $brandId . '#basic_id:' . $delId);
            mCustomCategoryWiki::update(['custom_state' => mCustomCategoryWiki::STATE_DEL], ['brand_id' => $brandId, 'basic_id' => $delId]);
        }
    }
    $basicIds = mCustomCategoryWiki::selectByWhere(['brand_id' => $brandId, 'custom_state' => mCustomCategoryWiki::STATE_NORMAL], 'basic_id');
    $list = mWikiBasic::selectByWhere(['basic_state' => mWikiBasic::STATE_ONLINE, 'id' => $basicIds, 'brand_id' => $brandId]);
    $list = array_column($list, null, 'id');
    foreach ($basicIds as $basicId) {
        if (!isset($list[$basicId])) {
            var_dump('查询品牌自定义分类下商品#删除自定义分类中非上线状态的品牌WIKI#brand_id:' . $brandId . '#basic_id:' . $delId);
            mCustomCategoryWiki::update(['custom_state' => mCustomCategoryWiki::STATE_DEL], ['brand_id' => $brandId, 'basic_id' => $basicId]);
        }
    }
}

